<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AdminUser;
use App\Models\AdminOperationLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

class AuthController extends Controller
{
    /**
     * A端管理员登录
     */
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 422,
                'message' => '参数验证失败',
                'data' => null,
                'errors' => $validator->errors()
            ], 422);
        }

        // 查找管理员用户
        $adminUser = AdminUser::where('email', $request->email)
                             ->where('status', AdminUser::STATUS_ACTIVE)
                             ->first();

        if (!$adminUser || !Hash::check($request->password, $adminUser->password)) {
            // 记录登录失败日志
            AdminOperationLog::create([
                'admin_user_id' => $adminUser->id ?? null,
                'action' => 'login',
                'module' => 'auth',
                'description' => '管理员登录失败',
                'ip_address' => $request->ip(),
                'user_agent' => $request->userAgent(),
                'result' => AdminOperationLog::RESULT_FAILED,
                'request_data' => json_encode([
                    'email' => $request->email,
                    'reason' => '邮箱或密码错误'
                ])
            ]);

            return response()->json([
                'code' => 401,
                'message' => '邮箱或密码错误',
                'data' => null
            ], 401);
        }

        // 更新最后登录信息
        $adminUser->updateLastLogin($request->ip());

        // 创建访问令牌
        $token = $adminUser->createToken('admin-auth-token')->plainTextToken;

        // 记录登录成功日志
        AdminOperationLog::create([
            'admin_user_id' => $adminUser->id,
            'action' => 'login',
            'module' => 'auth',
            'description' => '管理员登录成功',
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'result' => AdminOperationLog::RESULT_SUCCESS
        ]);

        return response()->json([
            'code' => 0,
            'message' => '登录成功',
            'data' => [
                'accessToken' => $token,
                'user' => [
                    'id' => $adminUser->id,
                    'username' => $adminUser->username,
                    'email' => $adminUser->email,
                    'name' => $adminUser->name,
                    'phone' => $adminUser->phone,
                    'role' => $adminUser->role,
                    'role_display' => $adminUser->role_display,
                    'status' => $adminUser->status,
                    'last_login_at' => $adminUser->last_login_at
                ],
                'permissions' => $this->getUserPermissions($adminUser)
            ]
        ]);
    }

    /**
     * A端管理员退出登录
     */
    public function logout(Request $request)
    {
        $user = $request->user();
        
        // 记录退出日志
        AdminOperationLog::create([
            'admin_user_id' => $user->id,
            'action' => 'logout',
            'module' => 'auth',
            'description' => '管理员退出登录',
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'result' => AdminOperationLog::RESULT_SUCCESS
        ]);

        // 删除当前访问令牌
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'code' => 0,
            'message' => '退出成功',
            'data' => null
        ]);
    }

    /**
     * 获取当前管理员信息
     */
    public function me(Request $request)
    {
        $user = $request->user();

        if (!$user) {
            return response()->json([
                'code' => 401,
                'message' => '用户未认证',
                'data' => null
            ], 401);
        }

        return response()->json([
            'code' => 0,
            'message' => '获取用户信息成功',
            'data' => [
                'id' => $user->id,
                'username' => $user->username,
                'email' => $user->email,
                'name' => $user->name,
                'phone' => $user->phone,
                'role' => $user->role,
                'role_display' => $user->role_display,
                'status' => $user->status,
                'status_display' => $user->status_display,
                'last_login_at' => $user->last_login_at,
                'created_at' => $user->created_at,
                'permissions' => $this->getUserPermissions($user)
            ]
        ]);
    }

    /**
     * 修改密码
     */
    public function changePassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'current_password' => 'required|string',
            'new_password' => 'required|string|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 422,
                'message' => '参数验证失败',
                'data' => null,
                'errors' => $validator->errors()
            ], 422);
        }

        $user = $request->user();

        // 验证当前密码
        if (!Hash::check($request->current_password, $user->password)) {
            return response()->json([
                'code' => 400,
                'message' => '当前密码错误',
                'data' => null
            ], 400);
        }

        // 更新密码
        $user->password = $request->new_password;
        $user->save();

        // 记录操作日志
        AdminOperationLog::create([
            'admin_user_id' => $user->id,
            'action' => 'change_password',
            'module' => 'auth',
            'description' => '管理员修改密码',
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'result' => AdminOperationLog::RESULT_SUCCESS
        ]);

        return response()->json([
            'code' => 0,
            'message' => '密码修改成功',
            'data' => null
        ]);
    }

    /**
     * 获取用户权限码
     */
    public function getAccessCodes(Request $request)
    {
        $user = $request->user();
        $permissions = $this->getUserPermissions($user);

        return response()->json([
            'code' => 0,
            'message' => '获取权限码成功',
            'data' => $permissions
        ]);
    }

    /**
     * 获取用户权限列表
     */
    private function getUserPermissions($user)
    {
        if ($user->role === AdminUser::ROLE_SUPER_ADMIN) {
            // 超级管理员拥有所有权限
            return ['*'];
        }

        return $user->permissions()->pluck('name')->toArray();
    }
}